package com.solution.wx.my.controller.finance;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.solution.admin.customer.entity.CustomerAccountEntity;
import com.solution.admin.customer.service.CustomerAccountService;
import com.solution.admin.finance.wallet.entity.WalletEntity;
import com.solution.admin.finance.wallet.entity.WalletFlowEntity;
import com.solution.admin.finance.wallet.entity.WalletWithdrawEntity;
import com.solution.admin.finance.wallet.service.WalletFlowService;
import com.solution.admin.finance.wallet.service.WalletService;
import com.solution.admin.finance.wallet.service.WalletWithdrawService;
import com.solution.common.controller.BaseController;
import com.solution.common.utils.StringUtils;

/**
 * 客户钱包提现web控制层
 * @author lufer
 * @date 2018-05-04 16:52:30
 */
@RequestMapping("/wx/my/wxWalletWithdraw")
@Controller
public class WxWalletWithdrawController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(WxWalletWithdrawController.class);

	@Autowired
	private WalletWithdrawService walletWithdrawService;
	@Autowired
	private WalletService walletService;
	@Autowired
	private CustomerAccountService customerAccountService;
	@Autowired
	private WalletFlowService walletFlowService;
	
	/**
	 * 跳转到提现选择账户类型界面
	 * @param WalletWithdraw 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lufer
 	 * @date 2018-05-04 16:52:30
	 */
	@RequestMapping("/toSelectAccountType")
	public String toListWalletWithdrawPage(HttpServletRequest request) {
		return "wx/my/wallet/withdraw_type";
	}
	
	/**
	 * 跳转提现页面
	 * @return string 跳转页面路径
	 * @author lufer
 	 * @date 2018-05-04 16:52:30
	 */
	@RequestMapping("/toAddWalletWithdraw")
	public String toAddWalletWithdraw(HttpServletRequest request) {
		return "/wx/my/wallet/withdraw_add";
	}

	/**
	 * 跳转选择账号界面
	 * @return string 跳转页面路径
	 * @author lufer
 	 * @date 2018-05-04 16:52:30
	 */
	@RequestMapping("/toSelectAccount")
	public String toSelectAccount(HttpServletRequest request) {
		return "/wx/my/wallet/withdraw_account";
	}


	/**
	 * 新增或保存客户钱包提现
	 * @param request 请求对象
	 * @param walletWithdrawEntity 客户钱包提现实体
	 * @return
	 * @author lufer
 	 * @date 2018-05-04 16:52:30
	 */
	@RequestMapping("/saveWalletWithdraw")
	@ResponseBody
	public Map<String, Object> saveWalletWithdraw(HttpServletRequest request, WalletWithdrawEntity walletWithdrawEntity) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		try {
			/***************查询当前登录客户财富汇总信息****************/
			Map<String, Object> paramMap = new HashMap<String, Object>();
			WalletEntity wallet = null;
			//从session中获取到当前登录客户ID
			Long customerId = getCustomerId();
			//封装查询参数
			paramMap.put("customerId", customerId);
			//查询当前登录客户的财富
			List<WalletEntity> walletList = walletService.listWallet(paramMap);
			//当前账号余额
			BigDecimal balanceMoney = new BigDecimal("0.00");
			if(null != walletList){
				Iterator<WalletEntity> it = walletList.iterator();
				if(it.hasNext()){
					wallet = (WalletEntity)it.next();
					if(null != wallet){
						balanceMoney = wallet.getGetableMoney();
					}
				}
			}
			//判断当前账户余额是否充足
			int r = balanceMoney.compareTo(walletWithdrawEntity.getWithdrawMoney());
			//如果账号余额小于提现金额则返回提示信息
			if(r==-1){
				resultMap.put("code", 0);
				resultMap.put("msg", "可提现金额不足");
				return resultMap;
			}
			
			/************************根据提现账号ID反查提现账号信息***************************/
			//从页面获取提现账号信息
			long accountId = Long.valueOf(request.getParameter("accountId"));
			//查询当前登录客户的提现账号信息
			CustomerAccountEntity caEntity = customerAccountService.getCustomerAccountById(accountId);
			if(null != caEntity){
				//状态为银行卡
				if("bank".equals(caEntity.getAccountType())){
					walletWithdrawEntity.setAccountNum(caEntity.getAccountCode());//银行卡号
					walletWithdrawEntity.setBankName(caEntity.getBankName()+caEntity.getSubBankName());//提现银行
				}else{//支付宝
					walletWithdrawEntity.setAccountNum(caEntity.getAlipayAccount());//支付宝账号
				}
				walletWithdrawEntity.setAccountType(caEntity.getAccountType());//账号类型
				walletWithdrawEntity.setAccountName(caEntity.getAccountName());//提现姓名
				walletWithdrawEntity.setWithdrawStatus(1);//提现状态默认为待审核
			}
			
			//封装到提现对象中
			walletWithdrawEntity.setCustomerId(customerId);//所属客户
			walletWithdrawEntity.setCustomerName(getUserName());//客户姓名
			walletWithdrawEntity.setBalanceMoney((balanceMoney.subtract(walletWithdrawEntity.getWithdrawMoney())).setScale(2));//此次提现后账户余额
			walletWithdrawEntity.setWithdrawMoney(walletWithdrawEntity.getWithdrawMoney().setScale(2));//保留2位小数
			//执行添加方法
			result = (int)walletWithdrawService.saveWalletWithdraw(walletWithdrawEntity);
			
			/***************如果提交提现申请成功，则把账户汇总统计中的可提现余额减去本次提现金额同时把提现中金额加上此次提现金额*******************/
			if(result>0){
				//可提现余额
				BigDecimal getableMoney = wallet.getGetableMoney();
				//提现中金额
				BigDecimal getingMoney = wallet.getGetingMoney();
				//可提现金额减去此次提现金额
				wallet.setGetableMoney((getableMoney.subtract(walletWithdrawEntity.getWithdrawMoney())).setScale(2));
				//提现中金额加上此次提现金额
				wallet.setGetingMoney((getingMoney.add(walletWithdrawEntity.getWithdrawMoney())).setScale(2));
				//修改账户
				int rs = walletService.updateWallet(wallet);
				/****************************账户余额变动则生产客户流水记录*************************/
				if(rs>0){
					WalletFlowEntity flowEntity = new WalletFlowEntity();
					//封装流水记录数据
					flowEntity.setCustomerId(customerId);//客户ID
					flowEntity.setFlowType("1");//类型为提现
					flowEntity.setPayType("0");//支出
					flowEntity.setOutMoney(walletWithdrawEntity.getWithdrawMoney());//支出金额
					flowEntity.setBalanceMoney((getableMoney.subtract(walletWithdrawEntity.getWithdrawMoney())).setScale(2));//当前账户余额
					flowEntity.setBillId(result);//提现单据ID
					//执行添加账号财务流水
					walletFlowService.saveWalletFlow(flowEntity);
				}
			}
			
			//返回结果
			resultMap.put("code", result);
		} catch (Exception e) {
			handleException("添加客户钱包提现失败", logger, e);
		}
		return resultMap;
	}
	
	/**
	 * 跳转到提现申请提交成功页面
	 * 作者：lufer
	 * 时间：2018年6月6日 下午5:27:54
	 * @param request
	 * @return
	 */
	@RequestMapping("/toWithdrawSuccessPage")
	public String toWithdrawSuccessPage(HttpServletRequest request) {
		/************************根据提现账号ID反查提现账号信息***************************/
		//从页面获取提现账号信息
		long accountId = Long.valueOf(request.getParameter("accountId"));
		//提现金额
		String withdrawMoney = request.getParameter("withdrawMoney");
		//查询当前登录客户的提现账号信息
		CustomerAccountEntity caEntity = customerAccountService.getCustomerAccountById(accountId);
		if(null != caEntity){
			if("bank".equals(caEntity.getAccountType())){
				String accountCode = StringUtils.substring(caEntity.getAccountCode(), caEntity.getAccountCode().length()-4, caEntity.getAccountCode().length());
				caEntity.setAccountCode(accountCode);
			}else{
				String alipayAccount = StringUtils.substring(caEntity.getAlipayAccount(),0, 3);
				caEntity.setAlipayAccount(alipayAccount);
			}
			request.setAttribute("caEntity", caEntity);
		}
		request.setAttribute("withdrawMoney", withdrawMoney);
		return "/wx/my/wallet/withdraw_add_success";
	}
	
}
